<template>
  <div class="app-header">
    <div class="user-info">
      <img :src="avatar" alt="头像" class="avatar" />
      <div class="user-meta">
        <div class="nickname">{{ nickname }}</div>
        <div class="title">{{ userTitle }}</div>
        <div v-if="isVIP" class="vip-badge">VIP</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useUserStore } from "../../store/modules/user";

// 静态导入默认头像
import defaultAvatar from "@/assets/avatars/default-avatar.png";

const userStore = useUserStore();

const user = computed(() => userStore.currentUser);
const nickname = computed(() => user.value?.nickname || "未登录用户");
const userTitle = computed(() => user.value?.title || "");
const isVIP = computed(() => user.value?.isVIP || false);

// 头像处理 - 支持动态和静态资源
const avatar = ref(defaultAvatar);

onMounted(() => {
  // 如果用户有自定义头像，动态设置
  if (user.value?.avatar) {
    try {
      // 安全的动态资源加载
      avatar.value = new URL(user.value.avatar, import.meta.url).href;
    } catch (error) {
      console.error("加载头像失败:", error);
      avatar.value = defaultAvatar;
    }
  }
});
</script>

<style scoped>
.app-header {
  padding: 12px;
  background: white;
  border-bottom: 1px solid #f0f0f0;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
  background-color: #f0f0f0; /* 头像加载前的背景色 */
}

.user-meta {
  flex-grow: 1;
}

.nickname {
  font-weight: bold;
  font-size: 16px;
}

.title {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.vip-badge {
  display: inline-block;
  background: linear-gradient(45deg, #ffd700, #ff9900);
  color: white;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  margin-top: 4px;
}
</style>
